// app/components/auth/LoginForm.tsx - 登录表单组件

'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { authService } from '@/lib/services/auth';
import Countdown from './countdown';

/**
 * @interface FormData
 * @description 登录表单数据接口
 * @property {string} [phone] - 手机号
 * @property {string} [email] - 邮箱
 * @property {string} [password] - 密码
 * @property {string} [verificationCode] - 验证码
 */
interface FormData {
  phone?: string;
  email?: string;
  password?: string;
  verificationCode?: string;
}

/**
 * @component LoginForm
 * @description 登录表单组件
 * @returns {JSX.Element} 登录表单界面
 */
export default function LoginForm() {
  const router = useRouter();
  const [loginType, setLoginType] = useState<'phone' | 'password'>('phone');
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState<FormData>({});
  const [showVerificationInput, setShowVerificationInput] = useState(false);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSendVerificationCode = async () => {
    if (!formData.phone) {
      alert('请输入手机号');
      return;
    }

    try {
      setLoading(true);
      await authService.sendVerificationCode({
        phone: formData.phone,
        type: 'login'
      });
      setShowVerificationInput(true);
    } catch (error) {
      console.error('发送验证码失败:', error);
      alert('发送验证码失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      if (loginType === 'phone' && (!formData.phone || !formData.verificationCode)) {
        alert('请输入手机号和验证码');
        return;
      }
      
      if (loginType === 'password' && (!formData.email || !formData.password)) {
        alert('请输入邮箱和密码');
        return;
      }

      let response;
      if (loginType === 'phone') {
        response = await authService.login({
          username_or_phone: formData.phone!,
          verification_code: formData.verificationCode!,
          login_type: 'phone'
        });
      } else {
        response = await authService.login({
          username_or_phone: formData.email!,
          password: formData.password!,
          login_type: 'password'
        });
      }

      if (response.data) {
        router.push('/dashboard');
      }
    } catch (error) {
      console.error('登录失败:', error);
      alert('登录失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="bg-white shadow-md rounded-lg p-8">
      <div className="flex mb-6 space-x-4">
        <button
          type="button"
          className={`flex-1 py-2 text-center rounded-md ${
            loginType === 'phone' ? 'bg-blue-50 text-blue-600' : 'text-gray-600'
          }`}
          onClick={() => setLoginType('phone')}
        >
          手机号登录
        </button>
        <button
          type="button"
          className={`flex-1 py-2 text-center rounded-md ${
            loginType === 'password' ? 'bg-blue-50 text-blue-600' : 'text-gray-600'
          }`}
          onClick={() => setLoginType('password')}
        >
          密码登录
        </button>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {loginType === 'phone' ? (
          <>
            <div>
              <label htmlFor="phone" className="block text-sm font-medium text-gray-700">
                手机号
              </label>
              <div className="mt-1">
                <input
                  id="phone"
                  name="phone"
                  type="tel"
                  required
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入手机号"
                  value={formData.phone || ''}
                  onChange={handleInputChange}
                  disabled={loading}
                />
              </div>
            </div>

            {showVerificationInput ? (
              <div>
                <label htmlFor="verificationCode" className="block text-sm font-medium text-gray-700">
                  验证码
                </label>
                <div className="mt-1 flex space-x-2">
                  <input
                    id="verificationCode"
                    name="verificationCode"
                    type="text"
                    required
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="请输入验证码"
                    value={formData.verificationCode || ''}
                    onChange={handleInputChange}
                    disabled={loading}
                  />
                  <Countdown onCountdownEnd={() => setShowVerificationInput(false)} />
                </div>
              </div>
            ) : (
              <button
                type="button"
                onClick={handleSendVerificationCode}
                disabled={loading || !formData.phone}
                className="w-full bg-blue-600 text-white py-2 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
              >
                获取验证码
              </button>
            )}
          </>
        ) : (
          <>
            <div>
              <label htmlFor="email" className="block text-sm font-medium text-gray-700">
                邮箱
              </label>
              <div className="mt-1">
                <input
                  id="email"
                  name="email"
                  type="email"
                  required
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入邮箱"
                  value={formData.email || ''}
                  onChange={handleInputChange}
                  disabled={loading}
                />
              </div>
            </div>

            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-700">
                密码
              </label>
              <div className="mt-1">
                <input
                  id="password"
                  name="password"
                  type="password"
                  required
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入密码"
                  value={formData.password || ''}
                  onChange={handleInputChange}
                  disabled={loading}
                />
              </div>
            </div>
          </>
        )}

        <button
          type="submit"
          disabled={loading}
          className="w-full bg-blue-600 text-white py-2 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
        >
          {loading ? '登录中...' : '登录'}
        </button>

        <div className="flex items-center justify-between text-sm">
          <a href="/signup" className="text-blue-600 hover:text-blue-500">
            注册账号
          </a>
          <a href="/forgot-password" className="text-blue-600 hover:text-blue-500">
            忘记密码？
          </a>
        </div>
      </form>
    </div>
  );
} 